//home模块的小仓库---四部分 state mutations actions getters
//state存储数据的地方
import { reqGetCode, reqRegister, reqLogin, reqUserInfo,reqLogOut} from "@/api";
import { SET_TOKEN,GET_TOKEN,REMOVE_TOKEN} from "@/utils/token";
const state = {
    code: '',
    //存储令牌
    token:GET_TOKEN(),
    nickName:''//用户名字
};
//mutations:唯一可以修改仓库数据的地方
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    SET_TOKEN(state, token) {
        state.token = token;
    },
    SET_NICKNAME(state,nickName){
        state.nickName = nickName;
    },
    LOGOUT(state){
        state.token = '';
        state.nickName = '';
        //本地存储token清除
        REMOVE_TOKEN();
    }

};
//actions:可以书写业务、逻辑
const actions = {
    //获取验证码
    async getCode({ state, commit, dispatch }, phone) {
        let result = await reqGetCode(phone);
        //实际开发,发完请求，就不管了！！！！
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok'
        } else {
            return Promise.reject();
        }
    },
    //注册
    async register({ state, commit, dispatch }, data) {
        let result = await reqRegister(data);
        console.log(result);
        if (result.code == 200) {
            //注册成功
            return 'ok';
        } else {
            return Promise.reject(result.message);
        }
    },
    //很重要*****
    async login({ state, commit, dispatch }, data) {
        //登录请求*****
        let result = await reqLogin(data);
        //如果登录成功：返回token---存储[用户信息]
        if (result.code == 200) {
            //登录成功
            commit('SET_TOKEN', result.data.token);
            //第一次遇见token:持久化存储令牌
            SET_TOKEN(result.data.token);
            return 'ok'
        } else {
            //登录失败
            return Promise.reject(result.message);
        }
    },
    //发请求获取用户信息
    async getUserInfo({state,commit,dispatch}) {
        let result = await reqUserInfo();
         if(result.code==200){
             //存储用户名字
             commit('SET_NICKNAME',result.data.nickName);
             return 'ok'
         }else{
             return Promise.reject();
         }
    },
    //退出登录
    async logout({commit,state,dispatch}){
      let result   = await reqLogOut(); 
      if(result.code==200){
          commit('LOGOUT');
          return 'ok';
      }else{
          return Promise.reject();
      }
    }

};
//计算属性getters
const getters = {};

//对外暴露小仓库
export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}


